package com.ly.jvm;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import	java.lang.ref.WeakReference;

import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

public class ReferenceDemo {

    public static void strongReference() {
        Object o1 = new Object();
        Object o2 = o1;
        o1 = null;
        System.gc();
        System.out.println(o1);
        System.out.println(o2);
    }

    public static void softReference() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(softReference.get());
        o1 = null;
        try{
            byte[] b = new byte[1024*1024*100];
        }catch(Exception e){

        }finally {
            System.out.println(softReference.get());
        }


    }

    public static void weakReference() {
        Object o1 = new Object();
        WeakReference<Object> reference = new WeakReference<>(o1);
        o1 = null;
        System.gc();
        System.out.println(o1);
        System.out.println(reference.get());

    }

    public static void weakHashMapReference() {
        WeakHashMap<Integer,Integer> weakHashMap = new WeakHashMap<>();
        Integer a = new Integer(1);
        Integer b = new Integer(2);
        weakHashMap.put(a,b);
//        b = null;
        a = null;
        System.out.println(weakHashMap);
        System.gc();
        System.out.println(weakHashMap);
    }


    public static void referenceQueue() {
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        WeakReference<Object> reference = new WeakReference<> (o1,referenceQueue);
        o1 = null;
        System.out.println(referenceQueue.poll());
        System.out.println(reference.get());
        System.gc();
        try {
            //等待引用放入队列
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(referenceQueue.poll());
        System.out.println(reference.get());
    }

    public static void phantomReference() {
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> phantomReference = new PhantomReference<>(o1,referenceQueue);

        System.out.println(o1);
        System.out.println(referenceQueue.poll());
        System.out.println(phantomReference.get());

        o1 = null;
        System.gc();

        System.out.println(o1);
        System.out.println(referenceQueue.poll());
        System.out.println(phantomReference.get());


    }



    public static void main(String[] args) {
//        strongReference();
//        softReference();
//        weakReference();
//        weakHashMapReference();
//        referenceQueue();
        phantomReference();
    }
}
